<?php

define('IN_ECS', true);
require(dirname(__FILE__) . '/includes/init.php');
require(ROOT_PATH . 'includes/lib_goods.php');
require_once(ROOT_PATH . 'includes/cls_image.php');

$exc = new exchange($ecs->table('coupons'), $db, 'cou_id', 'cou_name');

/* 允许上传的文件类型 */
$allow_file_types = '|GIF|JPG|PNG|BMP|SWF|DOC|XLS|PPT|MID|WAV|ZIP|RAR|PDF|CHM|RM|TXT|';
/*------------------------------------------------------ */
//-- 活动列表页
/*------------------------------------------------------ */

if ($_REQUEST['act'] == 'list')
{
    admin_priv('coupons_manage');

    /* 模板赋值 */
    $smarty->assign('full_page',   1);
    $smarty->assign('ur_here',     '优惠券列表');
    $smarty->assign('action_link', array('href' => 'rg_coupons.php?act=add', 'text' => '添加优惠券'));

    $list = coupons_list();

    $smarty->assign('coupons_list', $list['item']);
    $smarty->assign('filter',          $list['filter']);
    $smarty->assign('record_count',    $list['record_count']);
    $smarty->assign('page_count',      $list['page_count']);

    $sort_flag  = sort_flag($list['filter']);
    $smarty->assign($sort_flag['tag'], $sort_flag['img']);

    /* 显示商品列表页面 */
    assign_query_info();
    $smarty->display('rg_coupons_list.htm');
}

/*------------------------------------------------------ */
//-- 分页、排序、查询
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'query')
{
    $list = coupons_list();

    $smarty->assign('coupons_list', $list['item']);
    $smarty->assign('filter',          $list['filter']);
    $smarty->assign('record_count',    $list['record_count']);
    $smarty->assign('page_count',      $list['page_count']);

    $sort_flag  = sort_flag($list['filter']);
    $smarty->assign($sort_flag['tag'], $sort_flag['img']);

    make_json_result($smarty->fetch('rg_coupons_list.htm'), '', array('filter' => $list['filter'], 'page_count' => $list['page_count']));
}

/*------------------------------------------------------ */
//-- 删除
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'remove')
{
    check_authz_json('coupons_manage');

    $id = intval($_GET['id']);
    $coupons = coupons_info($id);
    if (empty($coupons)) make_json_error('该优惠券不存在。'); 
    $name = $coupons['cou_name'];
    if ($exc->drop($id)){
		$old_url = $coupons['cou_img'];
		if ($old_url != '' && strpos($old_url, 'http://') === false && strpos($old_url, 'https://') === false){
			@unlink(ROOT_PATH . $old_url);
		}
		$db->query("DELETE FROM ".$ecs->table('code')." WHERE code_id = '".$coupons['id_code']."'");
	}
    /* 记日志 */
    admin_log($name, 'remove', 'coupons');

    /* 清除缓存 */
    clear_cache_files();

    $url = 'rg_coupons.php?act=query&' . str_replace('act=remove', '', $_SERVER['QUERY_STRING']);

    ecs_header("Location: $url\n");
    exit;
}

/*------------------------------------------------------ */
//-- 添加、编辑
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'add' || $_REQUEST['act'] == 'edit')
{
    /* 检查权限 */
    admin_priv('coupons_manage');

    /* 是否添加 */
    $is_add = $_REQUEST['act'] == 'add';
    $smarty->assign('form_action', $is_add ? 'insert' : 'update');

    /* 初始化、取得优惠活动信息 */
    if ($is_add){
        $coupons = array( 'cou_id' => 0, 'cou_name' => '', 'start_time' => date('Y-m-d', time() + 86400), 'end_time' => date('Y-m-d', time() + 4 * 86400), 'user_rank' => '', 'cou_range' => FAR_ALL, 'cou_range_ext' => '');
    }else{
        if (empty($_GET['id'])) sys_msg('invalid param'); 
        $id = intval($_GET['id']);
        $coupons = coupons_info($id);
        if (empty($coupons)){
			sys_msg('该优惠券不存在。');
		}else{
			$coupons['code_name'] = $db->GetOne("SELECT code_name FROM " .$ecs->table('code'). " WHERE code_id='$coupons[id_code]'");
			$coupons['code_fee'] = $db->GetOne("SELECT code_fee FROM " .$ecs->table('code'). " WHERE code_id='$coupons[id_code]'");
			$coupons['code_type'] = $db->GetOne("SELECT code_type FROM " .$ecs->table('code'). " WHERE code_id='$coupons[id_code]'");
		}
    }
    $smarty->assign('coupons', $coupons);

    /* 取得用户等级 */
	$user_rank_list = array();
    $user_rank_list[] = array(
        'rank_id'   => 0,
        'rank_name' => '非会员',
        'checked'   => strpos(',' . $coupons['user_rank'] . ',', ',0,') !== false
    );
    $res = $db->query("SELECT rank_id, rank_name FROM " . $ecs->table('user_rank'));
    while ($row = $db->fetchRow($res)){
        $row['checked'] = strpos(',' . $coupons['user_rank'] . ',', ',' . $row['rank_id']. ',') !== false;
        $user_rank_list[] = $row;
    }
    $smarty->assign('user_rank_list', $user_rank_list);

    /* 取得优惠范围 */
    $cou_range_ext = array();
    if ($coupons['cou_range'] != 0 && !empty($coupons['cou_range_ext']))
    {
        if ($coupons['cou_range'] == 1){
            $sql = "SELECT cat_id AS id, cat_name AS name FROM " . $ecs->table('category') . " WHERE cat_id " . db_create_in($coupons['cou_range_ext']);
        }elseif ($coupons['cou_range'] == 2){
            $sql = "SELECT brand_id AS id, brand_name AS name FROM " . $ecs->table('brand') . " WHERE brand_id " . db_create_in($coupons['cou_range_ext']);
        }else{
            $sql = "SELECT goods_id AS id, goods_name AS name FROM " . $ecs->table('goods') . " WHERE goods_id " . db_create_in($coupons['cou_range_ext']);
        }
        $cou_range_ext = $db->getAll($sql);
    }
    $smarty->assign('cou_range_ext', $cou_range_ext);

    /* 赋值时间控件的语言 */
    $smarty->assign('cfg_lang', $_CFG['lang']);

    /* 显示模板 */
    if ($is_add) $smarty->assign('ur_here', '添加优惠券'); else $smarty->assign('ur_here', '编辑优惠券'); 
    $href = 'rg_coupons.php?act=list';
    if (!$is_add) $href .= '&' . list_link_postfix(); 
    $smarty->assign('action_link', array('href' => $href, 'text' => '优惠券列表'));
    assign_query_info();
    $smarty->display('rg_coupons_info.htm');
}

/*------------------------------------------------------ */
//-- 添加、编辑后提交
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'insert' || $_REQUEST['act'] == 'update')
{
    /* 检查权限 */
    admin_priv('coupons_manage');

    /* 是否添加 */
    $is_add = $_REQUEST['act'] == 'insert';
	
	if ($is_add){
		$is_code = $db->getOne("SELECT count(*) FROM ".$ecs->table("code")." WHERE code_name = '".$_POST['code_name']."'");
		if($is_code) sys_msg(sprintf("优惠码 %s 已经存在", stripslashes($_POST['code_name'])), 1);
	}
    $cou_name = sub_str($_POST['cou_name'], 255, false);
    if (!$exc->is_only('cou_name', $cou_name, intval($_POST['id']))) sys_msg('该优惠券名称已存在，请您换一个'); 

    /* 检查优惠范围扩展信息 */
    if (intval($_POST['cou_range']) > 0 && !isset($_POST['cou_range_ext'])) sys_msg('请设置优惠范围'); 

    /* 取得文件地址 */
    $file_url = '';
    if ((isset($_FILES['file']['error']) && $_FILES['file']['error'] == 0) || (!isset($_FILES['file']['error']) && isset($_FILES['file']['tmp_name']) && $_FILES['file']['tmp_name'] != 'none'))
    {
        // 检查文件格式
        if (!check_file_type($_FILES['file']['tmp_name'], $_FILES['file']['name'], $allow_file_types)) sys_msg($_LANG['invalid_file']); 

        // 复制文件
        $res = upload_article_file($_FILES['file']);
        if ($res != false) $file_url = $res; 
    }

    if ($file_url == '') $file_url = $_POST['file_url']; 

    /* 提交值 */
    $coupons = array(
        'cou_id'        => intval($_POST['id']),
        'cou_name'      => $cou_name,
        'start_time'    => local_strtotime($_POST['start_time']),
        'end_time'      => local_strtotime($_POST['end_time']),
        'user_rank'     => isset($_POST['user_rank']) ? join(',', $_POST['user_rank']) : '0',
        'cou_range'     => intval($_POST['cou_range']),
        'cou_range_ext' => intval($_POST['cou_range']) == 0 ? '' : join(',', $_POST['cou_range_ext']),
        'cou_img'       => $file_url
    );

    /* 保存数据 */
    if ($is_add){
		if ($coupons['cou_range'] == 1) $type_id = 2; elseif ($coupons['cou_range'] == 2) $type_id = 3; else $type_id = 4; 
		$db->query("INSERT INTO ".$ecs->table('code')." (code_name, code_fee, code_type, type_id) VALUES ('$_POST[code_name]', '$_POST[code_fee]', '$_POST[code_type]', '$type_id')");
		$new_code_id = $db->insert_id();
		if($new_code_id){
			$coupons['id_code'] = $new_code_id;
			$db->autoExecute($ecs->table('coupons'), $coupons, 'INSERT');
		}
    }else{
        $db->autoExecute($ecs->table('coupons'), $coupons, 'UPDATE', "cou_id = '$coupons[cou_id]'");
    }

    /* 记日志 */
    if ($is_add){
        admin_log($coupons['cou_name'], 'add', 'coupons');
    }else{
        admin_log($coupons['cou_name'], 'edit', 'coupons');
    }

    /* 清除缓存 */
    clear_cache_files();

    /* 提示信息 */
    if ($is_add){
        $links = array(
            array('href' => 'rg_coupons.php?act=add', 'text' => '继续添加优惠券'),
            array('href' => 'rg_coupons.php?act=list', 'text' => '返回优惠券列表')
        );
        sys_msg('成功添加优惠券', 0, $links);
    }else{
        $links = array( array('href' => 'rg_coupons.php?act=list&' . list_link_postfix(), 'text' => '返回优惠券列表') );
        sys_msg('成功编辑优惠券', 0, $links);
    }
}

/*------------------------------------------------------ */
//-- 搜索商品
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'search')
{
    /* 检查权限 */
    check_authz_json('coupons_manage');

    include_once(ROOT_PATH . 'includes/cls_json.php');

    $json   = new JSON;
    $filter = $json->decode($_GET['JSON']);
    $filter->keyword = json_str_iconv($filter->keyword);
    if ($filter->cou_range == 1){
        $sql = "SELECT cat_id AS id, cat_name AS name FROM " . $ecs->table('category') . " WHERE cat_name LIKE '%" . mysql_like_quote($filter->keyword) . "%' LIMIT 50";
        $arr = $db->getAll($sql);
    }elseif ($filter->cou_range == 2){
        $sql = "SELECT brand_id AS id, brand_name AS name FROM " . $ecs->table('brand') . " WHERE brand_name LIKE '%" . mysql_like_quote($filter->keyword) . "%' LIMIT 50";
        $arr = $db->getAll($sql);
    }else{
        $sql = "SELECT goods_id AS id, goods_name AS name FROM " . $ecs->table('goods') . " WHERE goods_name LIKE '%" . mysql_like_quote($filter->keyword) . "%' OR goods_sn LIKE '%" . mysql_like_quote($filter->keyword) . "%' LIMIT 50";
        $arr = $db->getAll($sql);
    }
    if (empty($arr)) $arr = array(0 => array( 'id'   => 0, 'name' => '没有找到相应记录，请重新搜索' )); 

    make_json_result($arr);
}

/*
 * 取得优惠活动列表
 * @return   array
 */
function coupons_list()
{
    $result = get_filter();
    if ($result === false)
    {
        /* 过滤条件 */
        $filter['keyword']    = empty($_REQUEST['keyword']) ? '' : trim($_REQUEST['keyword']);
        if (isset($_REQUEST['is_ajax']) && $_REQUEST['is_ajax'] == 1) $filter['keyword'] = json_str_iconv($filter['keyword']); 
        $filter['is_going']   = empty($_REQUEST['is_going']) ? 0 : 1;
        $filter['sort_by']    = empty($_REQUEST['sort_by']) ? 'cou_id' : trim($_REQUEST['sort_by']);
        $filter['sort_order'] = empty($_REQUEST['sort_order']) ? 'DESC' : trim($_REQUEST['sort_order']);

        $where = "";
        if (!empty($filter['keyword'])) $where .= " AND cou_name LIKE '%" . mysql_like_quote($filter['keyword']) . "%'"; 
        if ($filter['is_going']){
            $now = gmtime();
            $where .= " AND start_time <= '$now' AND end_time >= '$now' ";
        }

        $sql = "SELECT COUNT(*) FROM " . $GLOBALS['ecs']->table('coupons') . " WHERE 1 $where";
        $filter['record_count'] = $GLOBALS['db']->getOne($sql);

        /* 分页大小 */
        $filter = page_and_size($filter);

        /* 查询 */
        $sql = "SELECT * FROM " . $GLOBALS['ecs']->table('coupons') . " WHERE 1 $where ORDER BY $filter[sort_by] $filter[sort_order] LIMIT ". $filter['start'] .", $filter[page_size]";

        $filter['keyword'] = stripslashes($filter['keyword']);
        set_filter($filter, $sql);
    }else{
        $sql    = $result['sql'];
        $filter = $result['filter'];
    }
    $res = $GLOBALS['db']->query($sql);

    $list = array();
    while ($row = $GLOBALS['db']->fetchRow($res))
    {
        $row['start_time']  = local_date('Y-m-d H:i', $row['start_time']);
        $row['end_time']    = local_date('Y-m-d H:i', $row['end_time']);
		
        $row['code_name']    = $GLOBALS['db']->getOne("SELECT code_name FROM " .$GLOBALS['ecs']->table('code')." WHERE code_id = '".$row['id_code']."'");

        $list[] = $row;
    }

    return array('item' => $list, 'filter' => $filter, 'page_count' => $filter['page_count'], 'record_count' => $filter['record_count']);
}

/* 上传文件 */
function upload_article_file($upload)
{
    if (!make_dir("../" . DATA_DIR . "/coupons"))
    {
        /* 创建目录失败 */
        return false;
    }

    $filename = cls_image::random_filename() . substr($upload['name'], strpos($upload['name'], '.'));
    $path     = ROOT_PATH. DATA_DIR . "/coupons/" . $filename;

    if (move_upload_file($upload['tmp_name'], $path))
    {
        return DATA_DIR . "/coupons/" . $filename;
    }
    else
    {
        return false;
    }
}
?>